package logic

import (
	"context"
	"encoding/json"
	"product666/model/mysql"
	"product666/model/redis"
	"product666/userrpc/internal/svc"
	"product666/userrpc/userrpc"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *userrpc.ListRequest) (*userrpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	var findpro []mysql.Product

	get := redis.Client.Get("list" + strconv.Itoa(int(offset)))
	if get.Val() == "" {
		mysql.DB.Offset(int(offset)).Limit(int(pageSize)).Where("title like ?", "%"+in.Name+"%").Order("price desc").Find(&findpro)

		marshal, _ := json.Marshal(&findpro)

		redis.Client.Set("list"+strconv.Itoa(int(offset)), marshal, time.Hour*24)

	}

	var product []*userrpc.List
	for _, m := range findpro {
		list := userrpc.List{
			Id:       int64(m.ID),
			Title:    m.Title,
			Describe: m.Describe,
			Price:    float32(m.Price),
			UserId:   int64(m.UserId),
		}
		product = append(product, &list)
	}
	return &userrpc.ListResponse{List: product}, nil
}
